// pages/demo/demo.js
import regeneratorRuntime from '../../utils/runtime.js' // 引入模块
const app = getApp();
var ctx = null, // 创建canvas对象
    canvasToTempFilePath = null, // 保存最终生成的导出的图片地址
    openStatus = true; // 声明一个全局变量判断是否授权保存到相册

Page({
  /**
   * 页面的初始数据
   */
  data: {
    canvasbox: 'canvasbox',
    generateId: '',
    name: '蒋敬敏',
    shared: false,
  },

  /**
   * 用户点击右上角分享
   */
  onShareTap: function (event) {
    var itemsShared = wx.getStorageSync("shareState");
    var itemShared = false;
    var that = this;

    if (this.data.shared) { // 已分享
      // 分享提示
      wx.showToast({
        title: '您已分享成功',
        duration: 1000,
        icon: 'success'
      })
      itemShared = true;
    } else {  // 未分享
      var itemList = [
        '分享到朋友圈'
      ];
      wx.showActionSheet({
        itemList: itemList,
        itemColor: "#405f80",
        success: function (res) { 
          that.createCanvasImage();
        }
      })
      itemShared = false;
    }

    wx.setStorageSync("shareState", itemsShared);
    this.setData({
      shared: itemShared
    })
  },
  // 获取微信公众号二维码
  getCode: function () {
    return new Promise(function (resolve, reject) {
     api.fetch('/wechat/open/getQRCodeNormal', 'GET').then(res => {
        console.log(res, '获取微信公众号二维码')
        if (res.code == 200) {
          console.log(res.content, 'codeUrl')
          resolve(res.content)
        }
      }).catch(err => {
        console.log(err)
      })
      resolve(res.content)
    })
  },
  // 生成海报
  async createCanvasImage() {
    let that = this;
    // 点击生成海报数据埋点
    that.setData({
      generateId: '点击生成海报'
    })
    if (!ctx) {
      // let codeUrl = await that.getCode()
      let code = '../../images/qrcode.jpg'
      wx.showLoading({
        title: '绘制中...'
      })
      /* let code = new Promise(function (resolve) {
        wx.getImageInfo({
          src: codeUrl,
          success: function (res) {
            resolve(res.path)
          },
          fail: function (err) {
            console.log(err)
            wx.showToast({
              title: '网络错误请重试',
              icon: 'loading'
            })
          }
        })
      }) */
      let headImg = '../../images/avatar.jpg'
      /* let headImg = new Promise(function (resolve) {
        wx.getImageInfo({
          src: `${app.globalData.userInfo.avatarUrl}`,
          success: function (res) {
            resolve(res.path)
          },
          fail: function (err) {
            console.log(err)
            wx.showToast({
              title: '网络错误请重试',
              icon: 'loading'
            })
          }
        })
      }) */

      Promise.all([headImg, code]).then(function (result) {
        const ctx = wx.createCanvasContext('myCanvas')
        const ratio = app.globalData.ratio;
        let canvasWidthPx = 750,
          canvasHeightPx = 1206,
          avatarurl_width = 120/ratio,
          avatarurl_heigth = 120/ratio,
          avatarurl_x = 100/ratio,
          avatarurl_y = 500/ratio,
          codeurl_width = 160/ratio,
          codeurl_heigth = 160/ratio,
          codeurl_x = 290/ratio, 
          codeurl_y = 740/ratio;
          
        ctx.drawImage('../../images/shareimg.png', 30/ratio, 30/ratio, (canvasWidthPx-60)/ratio, (canvasHeightPx-30)/ratio-40)
        ctx.save(); // 先保存状态 已便于画完圆再用
        ctx.beginPath(); //开始绘制

        ctx.font = 'normal normal 14px sans-serif';
        ctx.setFillStyle('#ffffff'); 
        ctx.fillText('尊敬的客户您好，以下是给您推荐合适', 50/ratio, 80/ratio);  

        ctx.font = 'normal normal 14px sans-serif';
        ctx.setFillStyle('#ffffff'); 
        ctx.fillText('您公司的选址方案', 50/ratio, 120/ratio);

        ctx.drawImage('../../images/house.jpg', 50/ratio, 150/ratio, (canvasWidthPx-100)/ratio, 400/ratio); 

        //先画个圆   前两个参数确定了圆心 （x,y） 坐标  第三个参数是圆的半径  四参数是绘图方向  默认是false，即顺时针
        ctx.arc(avatarurl_width / 2 + avatarurl_x, avatarurl_heigth / 2 + avatarurl_y, avatarurl_width / 2, 0, Math.PI * 2, false);
        ctx.clip(); //画了圆 再剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内
        ctx.drawImage(result[0], avatarurl_x, avatarurl_y, avatarurl_width, avatarurl_heigth); // 推进去图片

        const metrics = ctx.measureText(that.data.name)
        const nameWidth = metrics.width/ratio
        let nameX = 0
        if(nameWidth > avatarurl_width){
          nameX = avatarurl_x - (nameWidth-avatarurl_width)/2
        }else{
          nameX = avatarurl_x + (avatarurl_width-nameWidth)/2
        }
        ctx.restore(); //恢复之前保存的绘图上下文状态 可以继续绘制
        ctx.setFillStyle('#ffffff'); 
        ctx.setFontSize(18); 
        ctx.fillText(that.data.name, 96/ratio, 670/ratio); 

        ctx.font = 'normal normal 16px sans-serif';
        ctx.setFillStyle('#ffffff'); 
        ctx.fillText('选址推荐方案', 470/ratio, 600/ratio);

        ctx.font = 'normal normal 14px sans-serif';
        ctx.setFillStyle('#ffffff'); 
        ctx.fillText('包含6个项目', 480/ratio, 650/ratio);

        ctx.drawImage(result[1], codeurl_x, codeurl_y, codeurl_width, codeurl_heigth); // 绘制二维码

        ctx.font = 'normal normal 14px sans-serif';
        ctx.setFillStyle('#ffffff'); 
        ctx.fillText('长按识别二维码', 270/ratio, 960/ratio);
        ctx.draw(false, function () {
          // canvas画布转成图片并返回图片地址
          wx.canvasToTempFilePath({
            canvasId: 'myCanvas',
            success: function (res) {
              canvasToTempFilePath = res.tempFilePath
              that.setData({
                showShareImg: true
              })
              that.setData({
                canvasbox: 'canvasbox top0'
              })
              wx.showToast({
                title: '绘制成功',
              })
            },
            fail: function () {
              wx.showToast({
                title: '绘制失败',
              })
            },
            complete: function () {
              wx.hideLoading()
              wx.hideToast()
            }
          })
        })
      })
    }
  },

  // 保存到系统相册
  saveShareImg: function () {
    let that = this;
    // 数据埋点点击保存学情海报
    that.setData({
      saveId: '保存学情海报'
    })
    // 获取用户是否开启用户授权相册
    if (!openStatus) {
      wx.openSetting({
        success: (result) => {
          if (result) {
            if (result.authSetting["scope.writePhotosAlbum"] === true) {
              openStatus = true;
              wx.saveImageToPhotosAlbum({
                filePath: canvasToTempFilePath,
                success() {
                  that.setData({
                    showShareImg: false
                  })
                  wx.showToast({
                    title: '图片保存成功，快去分享到朋友圈吧~',
                    icon: 'none',
                    duration: 3000
                  })
                },
                fail() {
                  wx.showToast({
                    title: '保存失败',
                    icon: 'none'
                  })
                }
              })
            }
          }
        },
        fail: () => { },
        complete: () => { }
      });
    } else {
      wx.getSetting({
        success(res) {
          // 如果没有则获取授权
          if (!res.authSetting['scope.writePhotosAlbum']) {
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success() {
                openStatus = true
                wx.saveImageToPhotosAlbum({
                  filePath: canvasToTempFilePath,
                  success() {
                    that.setData({
                      showShareImg: false
                    })
                    wx.showToast({
                      title: '图片保存成功，快去分享到朋友圈吧~',
                      icon: 'none',
                      duration: 3000
                    })
                  },
                  fail() {
                    wx.showToast({
                      title: '保存失败',
                      icon: 'none'
                    })
                  }
                })
              },
              fail() {
                // 如果用户拒绝过或没有授权，则再次打开授权窗口
                openStatus = false
                console.log('请设置允许访问相册')
                wx.showToast({
                  title: '请设置允许访问相册',
                  icon: 'none'
                })
              }
            })
          } else {
            // 有则直接保存
            openStatus = true
            var itemList = [
              '保存图片'
            ];
            wx.showActionSheet({
              itemList: itemList,
              itemColor: "#405f80",
              success: function (res) { 
                wx.saveImageToPhotosAlbum({
                  filePath: canvasToTempFilePath,
                  success() {
                    that.setData({
                      showShareImg: false
                    })
                    wx.showToast({
                      title: '图片保存成功，快去分享到朋友圈吧~',
                      icon: 'none',
                      duration: 3000
                    })
                  },
                  fail() {
                    wx.showToast({
                      title: '保存失败',
                      icon: 'none'
                    })
                  }
                })
              }
            })
          }
        },
        fail(err) {
          console.log(err)
        }
      })
    }
  }
})